﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _06_手动同步事件与自动同步事件
{
    public partial class Form1 : Form
    {
        //手动同步事件=> 构造函数传入参数的作用,是否设置为不阻塞状态 false:阻塞 true:不阻塞
        System.Threading.ManualResetEvent manualResetEvent = new System.Threading.ManualResetEvent(false);
        //自动同步事件 => 构造函数传入参数的作用,是否设置为不阻塞状态 false:阻塞 true:不阻塞
        System.Threading.AutoResetEvent autoResetEvent = new System.Threading.AutoResetEvent(false);

        public Form1()
        {
            InitializeComponent();
            //取消跨线程访问控件限制(创建出的工作线程可以自由访问主线程)
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 显示完毕窗体，启动线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Shown(object sender, EventArgs e)
        {
            //启动线程=>手动同步事件
            new Thread(() => 
            {
                for (int i = 0; i <= 100; i+=5)
                {
                    //使用手动同步事件=>阻塞当前线程(也可以解除对线程的阻塞)
                    manualResetEvent.WaitOne();
                    //更新进度条
                    this.progressBar1.Value = i;
                    //线程休眠
                    Thread.Sleep(200);
                }
            }) { IsBackground=true}.Start();
            //启动线程=>自动同步事件
            new Thread(() =>
            {
                for (int i = 0; i <= 100; i += 5)
                {
                    //使用自动同步事件=>阻塞当前线程(也可以解除对线程的阻塞)
                    autoResetEvent.WaitOne();
                    //更新进度条
                    this.progressBar2.Value = i;
                    //线程休眠
                    Thread.Sleep(200);
                }
            })
            { IsBackground = true }.Start();

        }
        /// <summary>
        /// Set
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //解除对线程的阻塞
            manualResetEvent.Set();
        }
        /// <summary>
        /// Reset
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //阻塞当前线程
            manualResetEvent.Reset();   
        }
        /// <summary>
        /// 自动同步事件=>Set
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            autoResetEvent.Set();
        }
    }
}
